package com.heima.datastructure.stack;

import com.heima.algorithm.recursion_multi.PascalTriangle;

import java.util.Iterator;

/**
 * 用单向链表实现栈
 * @param <E>
 */
public class LinkedListStack<E> implements Stack<E>, Iterable<E> {
    private final Node<E> head; // 头指针，用于指向栈顶的节点的前一个节点，也就是哨兵节点
    private int capacity; // 栈的容量
    private int size; // 栈的大小

    /**
     * 用构造函数初始化
     * @param capacity 容量
     */
    public LinkedListStack(int capacity) {
        this.capacity = capacity;
        this.size = 0;
        head = new Node<>(null,null);
    }

    /**
     * 节点类
     * @param <E>
     */
    private static class Node<E>{
        E value;
        Node<E> next;

        public Node(E value, Node<E> next) {
            this.value = value;
            this.next = next;
        }
    }

    /**
     * 向栈顶压入节点
     * @param value 待压入值
     * @return 压入成功返回true
     */
    @Override
    public boolean push(E value) {
        if (isFull()){
            return false;
        }
        head.next = new Node<>(value, head.next);
        size++;
        return true;
    }

    /**
     * 获取栈顶元素的值，并且弹出栈顶节点
     * @return 栈顶节点的值
     */
    @Override
    public E pop() {
        if (isEmpty()){
            return null;
        }
        Node<E> pop = head.next;
        head.next = pop.next;
        size--;
        return pop.value;
    }

    /**
     * 获取栈顶节点的值，不弹出
     * @return 栈顶节点的值
     */
    @Override
    public E peek() {
        if (isEmpty()){
            return null;
        }
        return head.next.value;
    }

    /**
     * 判断是否为空
     * @return 为空返回true
     */
    @Override
    public boolean isEmpty() {
        return size == 0;
    }

    /**
     * 判断是否为满
     * @return 为满返回true
     */
    @Override
    public boolean isFull() {
        return size == capacity;
    }

    /**
     * 迭代器，这个迭代器是从栈顶开始迭代
     * @return 迭代器
     */
    @Override
    public Iterator<E> iterator() {
        return new Iterator<E>() {
            Node<E> p = head.next;
            @Override
            public boolean hasNext() {
                return p != null;
            }

            @Override
            public E next() {
                E value = p.value;
                p = p.next;
                return value;
            }
        };
    }

    /**
     * 扩容
     * @param capacity 扩充到多少的容量
     */
    public void expansion(int capacity){
        if (capacity < this.capacity){
            throw new IllegalArgumentException("参数 [" + capacity + "] 不能比" + this.capacity + "小");
        }
        this.capacity = capacity;
    }
}
